<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    
    <title>第四十三章： 基于SpringBoot &amp; RabbitMQ完成TopicExchange分布式消息消费 | 恒宇少年De成长之路</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="我们在之前的两个章节第四十一章： 基于SpringBoot &amp;amp; RabbitMQ完成DirectExchange分布式消息消费、第四十二章： 基于SpringBoot &amp;amp; RabbitMQ完成DirectExchange分布式消息多消费者消费提高了RabbitMQ消息队列的DirectExchange交换类型的消息消费，我们之前的章节提到了RabbitMQ比较常用的交换类型有三种，">
<meta name="keywords" content="SpringBoot">
<meta property="og:type" content="article">
<meta property="og:title" content="第四十三章： 基于SpringBoot &amp; RabbitMQ完成TopicExchange分布式消息消费">
<meta property="og:url" content="http://blog.yuqiyu.com/spring-boot-chapter-43/index.html">
<meta property="og:site_name" content="恒宇少年De成长之路">
<meta property="og:description" content="我们在之前的两个章节第四十一章： 基于SpringBoot &amp;amp; RabbitMQ完成DirectExchange分布式消息消费、第四十二章： 基于SpringBoot &amp;amp; RabbitMQ完成DirectExchange分布式消息多消费者消费提高了RabbitMQ消息队列的DirectExchange交换类型的消息消费，我们之前的章节提到了RabbitMQ比较常用的交换类型有三种，">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-d80b777ca38632ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-01-23T15:55:44.160Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="第四十三章： 基于SpringBoot &amp; RabbitMQ完成TopicExchange分布式消息消费">
<meta name="twitter:description" content="我们在之前的两个章节第四十一章： 基于SpringBoot &amp;amp; RabbitMQ完成DirectExchange分布式消息消费、第四十二章： 基于SpringBoot &amp;amp; RabbitMQ完成DirectExchange分布式消息多消费者消费提高了RabbitMQ消息队列的DirectExchange交换类型的消息消费，我们之前的章节提到了RabbitMQ比较常用的交换类型有三种，">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/4461954-d80b777ca38632ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
    

    
        <link rel="alternate" href="/" title="恒宇少年De成长之路" type="application/atom+xml" />
    

    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">恒宇少年De成长之路</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">首页</a>
                
                    <a class="main-nav-link" href="/archives">时间轴</a>
                
                    <a class="main-nav-link" href="/categories">文章专题</a>
                
                    <a class="main-nav-link" href="/tags">标签云</a>
                
                    <a class="main-nav-link" href="/about">关于我</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/css/images/avatar.png" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <!--button type="submit" class="search-form-submit"></button-->
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td ><a  class="main-nav-link" href="/.">首页</a></td>
                
                    <td ><a  class="main-nav-link" href="/archives">时间轴</a></td>
                
                    <td ><a  class="main-nav-link" href="/categories">文章专题</a></td>
                
                    <td ><a  class="main-nav-link" href="/tags">标签云</a></td>
                
                    <td ><a  class="main-nav-link" href="/about">关于我</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/css/images/avatar.png" />
            <h2 id="name">恒宇少年</h2>
            <h3 id="title">Java软件工程师 &amp; 程序猿</h3>
            <span id="location"><i class="fa fa-map-marker"></i>山东, 济南</span>
            <a id="follow" target="_blank" href="https://www.jianshu.com/u/092df3f77bca">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                43
                <span>文章</span>
            </div>
            <div class="article-info-block">
                2
                <span>标签</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/ppoffice/hexo-theme-icarus" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="twitter" class=tooltip>
                            <i class="fa fa-twitter"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="facebook" class=tooltip>
                            <i class="fa fa-facebook"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="dribbble" class=tooltip>
                            <i class="fa fa-dribbble"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="post-spring-boot-chapter-43" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            第四十三章： 基于SpringBoot &amp; RabbitMQ完成TopicExchange分布式消息消费
        </h1>
    

                
                    <div class="article-meta">
                        
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/spring-boot-chapter-43/">
            <time datetime="2017-12-29T16:00:00.000Z" itemprop="datePublished">2017-12-30</time>
        </a>
    </div>


                        
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a>
    </div>

                        
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/SpringBoot/">SpringBoot</a>
    </div>

                    </div>
                
            </header>
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>我们在之前的两个章节<a href="https://www.jianshu.com/p/6b62a0ed2491" target="_blank" rel="noopener">第四十一章： 基于SpringBoot &amp; RabbitMQ完成DirectExchange分布式消息消费</a>、<a href="https://www.jianshu.com/p/4cccb48ccef7" target="_blank" rel="noopener">第四十二章： 基于SpringBoot &amp; RabbitMQ完成DirectExchange分布式消息多消费者消费</a>提高了<code>RabbitMQ</code>消息队列的<code>DirectExchange</code>交换类型的消息消费，我们之前的章节提到了<code>RabbitMQ</code>比较常用的交换类型有三种，我们今天来看看<code>TopicExchange</code>主题交换类型。<br><a id="more"></a></p>
<h1 id="本章目标"><a href="#本章目标" class="headerlink" title="本章目标"></a>本章目标</h1><p>基于<code>SpringBoot</code>平台完成<code>RabbitMQ</code>的<code>TopicExchange</code>消息类型交换。</p>
<h1 id="SpringBoot-企业级核心技术学习专题"><a href="#SpringBoot-企业级核心技术学习专题" class="headerlink" title="SpringBoot 企业级核心技术学习专题"></a>SpringBoot 企业级核心技术学习专题</h1><table>
<thead>
<tr>
<th style="text-align:center">专题</th>
<th style="text-align:left">专题名称</th>
<th style="text-align:left">专题描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">001</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/3f69deddbed3" target="_blank" rel="noopener">Spring Boot 核心技术</a></td>
<td style="text-align:left">讲解SpringBoot一些企业级层面的核心组件</td>
</tr>
<tr>
<td style="text-align:center">002</td>
<td style="text-align:left"><a href="https://gitee.com/hengboy/spring-boot-chapter" target="_blank" rel="noopener">Spring Boot 核心技术章节源码</a></td>
<td style="text-align:left">Spring Boot 核心技术简书每一篇文章码云对应源码</td>
</tr>
<tr>
<td style="text-align:center">003</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/1faac22666e7" target="_blank" rel="noopener">Spring Cloud 核心技术</a></td>
<td style="text-align:left">对Spring Cloud核心技术全面讲解</td>
</tr>
<tr>
<td style="text-align:center">004</td>
<td style="text-align:left"><a href="https://gitee.com/hengboy/spring-cloud-chapter" target="_blank" rel="noopener">Spring Cloud 核心技术章节源码</a></td>
<td style="text-align:left">Spring Cloud 核心技术简书每一篇文章对应源码</td>
</tr>
<tr>
<td style="text-align:center">005</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/ab4789177827" target="_blank" rel="noopener">QueryDSL 核心技术</a></td>
<td style="text-align:left">全面讲解QueryDSL核心技术以及基于SpringBoot整合SpringDataJPA</td>
</tr>
<tr>
<td style="text-align:center">006</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/f1b269bb2fd6" target="_blank" rel="noopener">SpringDataJPA 核心技术</a></td>
<td style="text-align:left">全面讲解SpringDataJPA核心技术</td>
</tr>
</tbody>
</table>
<h1 id="解决问题"><a href="#解决问题" class="headerlink" title="解决问题"></a>解决问题</h1><p>之前少年也遇到了一个问题，分类了多模块后消息队列无法自动创建，说来也好笑，之前没有时间去看这个问题，今天在编写本章文章时发现原因竟然是<code>SpringBoot</code>没有扫描到<code>common</code>模块内的配置类。让我一阵的头大~~~，我们在<code>XxxApplication</code>启动类上添加<code>@ComponentScan(value = &quot;com.hengyu.rabbitmq&quot;)</code>就可以自动创建队列了！！！</p>
<h1 id="构建项目"><a href="#构建项目" class="headerlink" title="构建项目"></a>构建项目</h1><p>本章构建项目时同样采用多模块的方式进行设计，可以很好的看到消息处理的效果，因为是多模块项目，我们先来创建一个<code>SpringBoot</code>项目，<code>pom.xml</code>配置文件依赖配置如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependencies&gt;</span><br><span class="line">        &lt;!--rabbbitMQ相关依赖--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-amqp&lt;/artifactId&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--web相关依赖--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--lombok依赖--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;lombok&lt;/artifactId&gt;</span><br><span class="line">            &lt;optional&gt;true&lt;/optional&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--spring boot tester--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;</span><br><span class="line">            &lt;scope&gt;test&lt;/scope&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--fast json依赖--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;com.alibaba&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;fastjson&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;1.2.40&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">    &lt;/dependencies&gt;</span><br></pre></td></tr></table></figure></p>
<p>下面我们先来构建公共<code>RabbitMQ</code>模块，因为我们的消费者以及生产者都是需要<code>RabbitMQ</code>相关的配置信息，这里我们可以提取出来，使用时进行模块之间的引用。</p>
<h3 id="rabbitmq-topic-common"><a href="#rabbitmq-topic-common" class="headerlink" title="rabbitmq-topic-common"></a>rabbitmq-topic-common</h3><p>创建子模块<code>rabbitmq-topic-common</code>，在<code>resources</code>下添加<code>application.yml</code>配置文件并配置<code>RabbitMQ</code>相关的依赖配置，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">spring:</span><br><span class="line">  #rabbitmq消息队列配置信息</span><br><span class="line">  rabbitmq:</span><br><span class="line">    host: 127.0.0.1</span><br><span class="line">    port: 5672</span><br><span class="line">    username: guest</span><br><span class="line">    password: guest</span><br><span class="line">    virtual-host: /</span><br><span class="line">    publisher-confirms: true</span><br></pre></td></tr></table></figure></p>
<h5 id="定义交换配置信息"><a href="#定义交换配置信息" class="headerlink" title="定义交换配置信息"></a>定义交换配置信息</h5><p>我们跟之前的章节一张，独立编写一个枚举类型来配置消息队列的交换信息，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * rabbitmq交换配置枚举</span><br><span class="line"> * ========================</span><br><span class="line"> *</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/11/26</span><br><span class="line"> * Time：13:56</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Getter</span><br><span class="line">public enum ExchangeEnum</span><br><span class="line">&#123;</span><br><span class="line">    /**</span><br><span class="line">     * 用户注册交换配置枚举</span><br><span class="line">     */</span><br><span class="line">    USER_REGISTER_TOPIC_EXCHANGE(&quot;register.topic.exchange&quot;)</span><br><span class="line">    ;</span><br><span class="line">    private String name;</span><br><span class="line"></span><br><span class="line">    ExchangeEnum(String name) &#123;</span><br><span class="line">        this.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h5 id="定义队列配置信息"><a href="#定义队列配置信息" class="headerlink" title="定义队列配置信息"></a>定义队列配置信息</h5><p>同样消息队列的基本信息配置也同样采用枚举的形式配置，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 队列配置枚举</span><br><span class="line"> * ========================</span><br><span class="line"> *</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/11/26</span><br><span class="line"> * Time：14:05</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Getter</span><br><span class="line">public enum QueueEnum</span><br><span class="line">&#123;</span><br><span class="line">    /**</span><br><span class="line">     * 用户注册</span><br><span class="line">     * 创建账户消息队列</span><br><span class="line">     */</span><br><span class="line">    USER_REGISTER_CREATE_ACCOUNT(&quot;register.account&quot;,&quot;register.#&quot;),</span><br><span class="line">    /**</span><br><span class="line">     * 用户注册</span><br><span class="line">     * 发送注册成功邮件消息队列</span><br><span class="line">     */</span><br><span class="line">    USER_REGISTER_SEND_MAIL(&quot;register.mail&quot;,&quot;register.#&quot;)</span><br><span class="line">    ;</span><br><span class="line">    /**</span><br><span class="line">     * 队列名称</span><br><span class="line">     */</span><br><span class="line">    private String name;</span><br><span class="line">    /**</span><br><span class="line">     * 队列路由键</span><br><span class="line">     */</span><br><span class="line">    private String routingKey;</span><br><span class="line"></span><br><span class="line">    QueueEnum(String name, String routingKey) &#123;</span><br><span class="line">        this.name = name;</span><br><span class="line">        this.routingKey = routingKey;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>消息队列枚举内添加了两个属性，分别对应了<code>队列名称</code>、<code>队列路由</code>，我们本章所讲解的<code>TopicExchange</code>类型消息队列可以根据路径信息配置多个消息消费者，而转发的匹配规则信息则是我们定义的队列的路由信息。</p>
<h5 id="定义发送消息路由信息"><a href="#定义发送消息路由信息" class="headerlink" title="定义发送消息路由信息"></a>定义发送消息路由信息</h5><p>我们在发送消息到队列时，需要我们传递一个路由相关的配置信息，<code>RabbitMQ</code>会根据发送时的消息路由规则信息与定义消息队列时的路由信息进行匹配，如果可以匹配则调用该队列的消费者完成消息的消费，发送消息路由信息配置如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 消息队列topic交换路由key配置枚举</span><br><span class="line"> * ========================</span><br><span class="line"> *</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/12/11</span><br><span class="line"> * Time：21:58</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Getter</span><br><span class="line">public enum TopicEnum &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 用户注册topic路由key配置</span><br><span class="line">     */</span><br><span class="line">    USER_REGISTER(&quot;register.user&quot;)</span><br><span class="line">    ;</span><br><span class="line"></span><br><span class="line">    private String topicRouteKey;</span><br><span class="line"></span><br><span class="line">    TopicEnum(String topicRouteKey) &#123;</span><br><span class="line">        this.topicRouteKey = topicRouteKey;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h6 id="路由特殊字符"><a href="#路由特殊字符" class="headerlink" title="路由特殊字符 #"></a>路由特殊字符 <code>#</code></h6><p>我们在<code>QueueEnum</code>内配置的<code>路由键</code>时有个特殊的符号：<code>#</code>，在<code>RabbitMQ</code>消息队列内路由配置<code>#</code>时表示可以匹配零个或多个字符，我们<code>TopicEnum</code>枚举内定义的<code>register.user</code>，则是可以匹配<code>QueueEnum</code>枚举定义<code>register.#</code>队列的路由规则。<br>当然发送消息时如果路由传递：<code>register.user.account</code>也是可以同样匹配<code>register.#</code>的路由规则。</p>
<h6 id="路由特殊字符-1"><a href="#路由特殊字符-1" class="headerlink" title="路由特殊字符 *"></a>路由特殊字符 <code>*</code></h6><p>除此之外比较常用到的特殊字符还有一个<code>*</code>，在<code>RabbitMQ</code>消息队列内路由配置<code>*</code>时表示可以匹配一个字符，我们<code>QueueEnum</code>定义路由键如果修改成<code>register.*</code>时，发送消息时路由为<code>register.user</code>则是可以接受到消息的。但如果发送时的路由为<code>register.user.account</code>时，则是无法匹配该消息。</p>
<h4 id="消息队列配置"><a href="#消息队列配置" class="headerlink" title="消息队列配置"></a>消息队列配置</h4><p>配置准备工作已经做好，接下来我们开始配置队列相关的内容，跟之前一样我们需要配置<code>Queue</code>、<code>Exchange</code>、<code>Binding</code>将消息队列与交换绑定。下面我们来看看配置跟之前的章节有什么差异的地方，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 用户注册消息队列配置</span><br><span class="line"> * ========================</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/11/26</span><br><span class="line"> * Time：16:58</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Configuration</span><br><span class="line">public class UserRegisterQueueConfiguration &#123;</span><br><span class="line"></span><br><span class="line">    private Logger logger = LoggerFactory.getLogger(UserRegisterQueueConfiguration.class);</span><br><span class="line">    /**</span><br><span class="line">     * 配置用户注册主题交换</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Bean</span><br><span class="line">    public TopicExchange userTopicExchange()</span><br><span class="line">    &#123;</span><br><span class="line">        TopicExchange topicExchange = new TopicExchange(ExchangeEnum.USER_REGISTER_TOPIC_EXCHANGE.getName());</span><br><span class="line">        logger.info(&quot;用户注册交换实例化成功。&quot;);</span><br><span class="line">        return topicExchange;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 配置用户注册</span><br><span class="line">     * 发送激活邮件消息队列</span><br><span class="line">     * 并设置持久化队列</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Bean</span><br><span class="line">    public Queue sendRegisterMailQueue()</span><br><span class="line">    &#123;</span><br><span class="line">        Queue queue = new Queue(QueueEnum.USER_REGISTER_SEND_MAIL.getName());</span><br><span class="line">        logger.info(&quot;创建用户注册消息队列成功&quot;);</span><br><span class="line">        return queue;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 配置用户注册</span><br><span class="line">     * 创建账户消息队列</span><br><span class="line">     * 并设置持久化队列</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Bean</span><br><span class="line">    public Queue createAccountQueue()</span><br><span class="line">    &#123;</span><br><span class="line">        Queue queue = new Queue(QueueEnum.USER_REGISTER_CREATE_ACCOUNT.getName());</span><br><span class="line">        logger.info(&quot;创建用户注册账号队列成功.&quot;);</span><br><span class="line">        return queue;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 绑定用户发送注册激活邮件队列到用户注册主题交换配置</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Bean</span><br><span class="line">    public Binding sendMailBinding(TopicExchange userTopicExchange,Queue sendRegisterMailQueue)</span><br><span class="line">    &#123;</span><br><span class="line">        Binding binding = BindingBuilder.bind(sendRegisterMailQueue).to(userTopicExchange).with(QueueEnum.USER_REGISTER_SEND_MAIL.getRoutingKey());</span><br><span class="line">        logger.info(&quot;绑定发送邮件到注册交换成功&quot;);</span><br><span class="line">        return binding;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 绑定用户创建账户到用户注册主题交换配置</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Bean</span><br><span class="line">    public Binding createAccountBinding(TopicExchange userTopicExchange,Queue createAccountQueue)</span><br><span class="line">    &#123;</span><br><span class="line">        Binding binding = BindingBuilder.bind(createAccountQueue).to(userTopicExchange).with(QueueEnum.USER_REGISTER_CREATE_ACCOUNT.getRoutingKey());</span><br><span class="line">        logger.info(&quot;绑定创建账号到注册交换成功。&quot;);</span><br><span class="line">        return binding;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们从上面开始分析。<br>第一步： 首先我们创建了<code>TopicExchange</code>消息队列对象，使用<code>ExchangeEnum</code>枚举内的<code>USER_REGISTER_TOPIC_EXCHANGE</code>类型作为交换名称。</p>
<p>第二步：我们创建了发送注册邮件的队列<code>sendRegisterMailQueue</code>，使用<code>QueueEnum</code>枚举内的类型<code>USER_REGISTER_SEND_MAIL</code>作为队列名称。</p>
<p>第三步：与发送邮件队列一致，用户创建完成后需要初始化账户信息，而<code>createAccountQueue</code>消息队列后续逻辑就是来完成该工作，使用<code>QueueEnum</code>枚举内的<code>USER_REGISTER_CREATE_ACCOUNT</code>枚举作为创建账户队列名称。</p>
<p>第四步：在上面步骤中已经将交换、队列创建完成，下面就开始将队列绑定到用户注册交换，从而实现注册用户消息队列消息消费，<code>sendMailBinding</code>绑定了<code>QueueEnum.USER_REGISTER_SEND_MAIL</code>的<code>RoutingKey</code>配置信息。</p>
<p><code>createAccountBinding</code>绑定了<code>QueueEnum.USER_REGISTER_CREATE_ACCOUNT</code>的<code>RoutingKey</code>配置信息。</p>
<p>到目前为止我们完成了<code>rabbitmq-topic-common</code>模块的所有配置信息，下面我们开始编写用户注册消息消费者模块。</p>
<h3 id="rabbitmq-topic-consumer"><a href="#rabbitmq-topic-consumer" class="headerlink" title="rabbitmq-topic-consumer"></a>rabbitmq-topic-consumer</h3><p>我们首先来创建一个子模块命名为<code>rabbitmq-topic-consumer</code>，在<code>pom.xml</code>配置文件内添加<code>rabbitmq-topic-common</code>模块的引用，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">....//</span><br><span class="line">&lt;dependencies&gt;</span><br><span class="line">        &lt;!--公共模块依赖--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;com.hengyu&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;rabbitmq-topic-common&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;$&#123;parent.version&#125;&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">    &lt;/dependencies&gt;</span><br><span class="line">....//</span><br></pre></td></tr></table></figure></p>
<h5 id="消费者程序入口"><a href="#消费者程序入口" class="headerlink" title="消费者程序入口"></a>消费者程序入口</h5><p>下面我们来创建程序启动类<code>RabbitMqTopicConsumerApplication</code>，在这里需要注意，手动配置下扫描路径<code>@ComponentScan</code>，启动类代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 消息消费者程序启动入口</span><br><span class="line"> * ========================</span><br><span class="line"> *</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/12/11</span><br><span class="line"> * Time：21:48</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@SpringBootApplication</span><br><span class="line">@ComponentScan(value = &quot;com.hengyu.rabbitmq&quot;)</span><br><span class="line">public class RabbitMqTopicConsumerApplication &#123;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * logback</span><br><span class="line">     */</span><br><span class="line">    private static Logger logger = LoggerFactory.getLogger(RabbitMqTopicConsumerApplication.class);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 程序入口</span><br><span class="line">     * @param args</span><br><span class="line">     */</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        SpringApplication.run(RabbitMqTopicConsumerApplication.class,args);</span><br><span class="line"></span><br><span class="line">        logger.info(&quot;【【【【【Topic队列消息Consumer启动成功】】】】】&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>手动配置扫描路径在文章的开始解释过了，主要目的是为了扫描到<code>RabbitMQConfiguration</code>配置类内的信息，让<code>RabbitAdmin</code>自动创建配置信息到<code>server</code>端。</p>
<h5 id="发送邮件消费者"><a href="#发送邮件消费者" class="headerlink" title="发送邮件消费者"></a>发送邮件消费者</h5><p>发送邮件消息费监听<code>register.mail</code>消息队列信息，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 发送用户注册成功邮件消费者</span><br><span class="line"> * ========================</span><br><span class="line"> *</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/12/11</span><br><span class="line"> * Time：22:07</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Component</span><br><span class="line">@RabbitListener(queues = &quot;register.mail&quot;)</span><br><span class="line">public class SendMailConsumer</span><br><span class="line">&#123;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * logback</span><br><span class="line">     */</span><br><span class="line">    Logger logger = LoggerFactory.getLogger(SendMailConsumer.class);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 处理消息</span><br><span class="line">     * 发送用户注册成功邮件</span><br><span class="line">     * @param userId 用户编号</span><br><span class="line">     */</span><br><span class="line">    @RabbitHandler</span><br><span class="line">    public void handler(String userId)</span><br><span class="line">    &#123;</span><br><span class="line"></span><br><span class="line">        logger.info(&quot;用户：&#123;&#125;，注册成功，自动发送注册成功邮件.&quot;,userId);</span><br><span class="line"></span><br><span class="line">        //... 发送注册成功邮件逻辑</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在这里我只是完成了消息的监听，具体的业务逻辑可以根据需求进行处理。</p>
<h5 id="创建账户消费者"><a href="#创建账户消费者" class="headerlink" title="创建账户消费者"></a>创建账户消费者</h5><p>创建用户账户信息消费者监听队列<code>register.account</code>，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * ========================</span><br><span class="line"> *</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/12/11</span><br><span class="line"> * Time：22:04</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Component</span><br><span class="line">@RabbitListener(queues = &quot;register.account&quot;)</span><br><span class="line">public class CreateAccountConsumer &#123;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * logback</span><br><span class="line">     */</span><br><span class="line">    Logger logger = LoggerFactory.getLogger(CreateAccountConsumer.class);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 处理消息</span><br><span class="line">     * 创建用户账户</span><br><span class="line">     * @param userId 用户编号</span><br><span class="line">     */</span><br><span class="line">    @RabbitHandler</span><br><span class="line">    public void handler(String userId)</span><br><span class="line">    &#123;</span><br><span class="line">        logger.info(&quot;用户：&#123;&#125;，注册成功，自动创建账户信息.&quot;,userId);</span><br><span class="line"></span><br><span class="line">        //... 创建账户逻辑</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>创建账户，账户初始化逻辑都可以在<code>handler</code>方法进行处理，本章没有做数据库复杂的处理，所以没有过多的逻辑处理在消费者业务内。</p>
<h3 id="rabbitmq-topic-provider"><a href="#rabbitmq-topic-provider" class="headerlink" title="rabbitmq-topic-provider"></a>rabbitmq-topic-provider</h3><p>接下来是我们的消息提供者的模块编写，我们依然先来创建程序入口类，并添加扫描配置<code>@ComponentScan</code>路径，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 消息生产者程序启动入口</span><br><span class="line"> * ========================</span><br><span class="line"> *</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/12/11</span><br><span class="line"> * Time：21:48</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@SpringBootApplication</span><br><span class="line">@ComponentScan(value = &quot;com.hengyu.rabbitmq&quot;)</span><br><span class="line">public class RabbitMqTopicProviderApplication &#123;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * logback</span><br><span class="line">     */</span><br><span class="line">    private static Logger logger = LoggerFactory.getLogger(RabbitMqTopicProviderApplication.class);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 程序入口</span><br><span class="line">     * @param args</span><br><span class="line">     */</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        SpringApplication.run(RabbitMqTopicProviderApplication.class,args);</span><br><span class="line"></span><br><span class="line">        logger.info(&quot;【【【【【Topic队列消息Provider启动成功】】】】】&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h5 id="定义消息发送接口"><a href="#定义消息发送接口" class="headerlink" title="定义消息发送接口"></a>定义消息发送接口</h5><p>创建<code>QueueMessageService</code>队列消息发送接口并添加<code>send</code>方法，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 消息队列业务</span><br><span class="line"> * ========================</span><br><span class="line"> *</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/11/26</span><br><span class="line"> * Time：14:50</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">public interface QueueMessageService</span><br><span class="line">&#123;</span><br><span class="line">    /**</span><br><span class="line">     * 发送消息到rabbitmq消息队列</span><br><span class="line">     * @param message 消息内容</span><br><span class="line">     * @param exchangeEnum 交换配置枚举</span><br><span class="line">     * @param routingKey 路由key</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    public void send(Object message, ExchangeEnum exchangeEnum, String routingKey) throws Exception;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><code>send</code>方法内有三个参数，解析如下：</p>
<ul>
<li>message：发送消息内容，可以为任意类型，当然本章内仅仅是java.lang.String。</li>
<li>exchangeEnum：我们自定义的交换枚举类型，方便发送消息到指定交换。</li>
<li>routingKey：发送消息时的路由键内容，该值采用<code>TopicEnum</code>枚举内的<code>topicRouteKey</code>作为参数值。</li>
</ul>
<p>下面我们来看看该接口的实现类<code>QueueMessageServiceSupport</code>内<code>send</code>方法实现，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 消息队列业务逻辑实现</span><br><span class="line"> * ========================</span><br><span class="line"> *</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/11/26</span><br><span class="line"> * Time：14:52</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Component</span><br><span class="line">public class QueueMessageServiceSupport</span><br><span class="line">    implements QueueMessageService</span><br><span class="line">&#123;</span><br><span class="line">    /**</span><br><span class="line">     * 消息队列模板</span><br><span class="line">     */</span><br><span class="line">    @Autowired</span><br><span class="line">    private RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void send(Object message, ExchangeEnum exchangeEnum, String routingKey) throws Exception &#123;</span><br><span class="line">        //发送消息到消息队列</span><br><span class="line">        rabbitTemplate.convertAndSend(exchangeEnum.getName(),routingKey,message);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们通过<code>RabbitTemplate</code>实例的<code>convertAndSend</code>方法将对象类型转换成<code>JSON</code>字符串后发送到消息队列服务端，<code>RabbitMQ</code>接受到消息后根据注册的消费者并且路由规则筛选后进行消息转发，并实现消息的消费。</p>
<h1 id="运行测试"><a href="#运行测试" class="headerlink" title="运行测试"></a>运行测试</h1><p>为了方便测试我们创建一个名为<code>UserService</code>的实现类，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 用户业务逻辑</span><br><span class="line"> * ========================</span><br><span class="line"> *</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/12/11</span><br><span class="line"> * Time：22:10</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@Service</span><br><span class="line">public class UserService</span><br><span class="line">&#123;</span><br><span class="line">    /**</span><br><span class="line">     * 消息队列发送业务逻辑</span><br><span class="line">     */</span><br><span class="line">    @Autowired</span><br><span class="line">    private QueueMessageService queueMessageService;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 随机创建用户</span><br><span class="line">     * 随机生成用户uuid编号，发送到消息队列服务端</span><br><span class="line">     * @return</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    public String randomCreateUser() throws Exception</span><br><span class="line">    &#123;</span><br><span class="line">        //用户编号</span><br><span class="line">        String userId = UUID.randomUUID().toString();</span><br><span class="line">        //发送消息到rabbitmq服务端</span><br><span class="line">        queueMessageService.send(userId, ExchangeEnum.USER_REGISTER_TOPIC_EXCHANGE, TopicEnum.USER_REGISTER.getTopicRouteKey());</span><br><span class="line">        return userId;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该类内添加了一个名为<code>randomCreateUser</code>随机创建用户的方法，通过<code>UUID</code>随机生成字符串作为用户的编号进行传递给用户注册消息队列，完成用户的模拟创建。</p>
<h5 id="编写测试用例"><a href="#编写测试用例" class="headerlink" title="编写测试用例"></a>编写测试用例</h5><p>接下来我们创建<code>RabbitMqTester</code>测试类来完成随机用户创建消息发送，测试用例完成简单的<code>UserService</code>注入，并调用<code>randomCreateUser</code>方法，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * ========================</span><br><span class="line"> *</span><br><span class="line"> * @author 恒宇少年</span><br><span class="line"> * Created with IntelliJ IDEA.</span><br><span class="line"> * Date：2017/12/11</span><br><span class="line"> * Time：22:10</span><br><span class="line"> * 码云：http://git.oschina.net/jnyqy</span><br><span class="line"> * ========================</span><br><span class="line"> */</span><br><span class="line">@RunWith(SpringRunner.class)</span><br><span class="line">@SpringBootTest(classes = RabbitMqTopicProviderApplication.class)</span><br><span class="line">public class RabbitMqTester</span><br><span class="line">&#123;</span><br><span class="line">    /**</span><br><span class="line">     * 用户业务逻辑</span><br><span class="line">     */</span><br><span class="line">    @Autowired</span><br><span class="line">   private UserService userService;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 模拟随机创建用户 &amp; 发送消息到注册用户消息队列</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    @Test</span><br><span class="line">    public void testTopicMessage() throws Exception</span><br><span class="line">    &#123;</span><br><span class="line">        userService.randomCreateUser();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>到目前为止，我们的编码已经完成，下面我们按照下面的步骤启动测试：</p>
<blockquote>
<ol>
<li>启动<code>rabbitmq-topic-consumer</code>消息消费者模块，并查看控制台输出内容是否正常</li>
<li>运行<code>rabbitmq-topic-provider</code>模块测试用例方法<code>testTopicMessage</code></li>
<li>查看<code>rabbitmq-topic-consumer</code>控制台输出内容</li>
</ol>
</blockquote>
<p>最终效果：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">2017-12-30 18:39:16.819  INFO 2781 --- [           main] c.h.r.c.RabbitMqTopicConsumerApplication : 【【【【【Topic队列消息Consumer启动成功】】】】】</span><br><span class="line">2017-12-30 18:39:29.376  INFO 2781 --- [cTaskExecutor-1] c.h.r.consumer.CreateAccountConsumer     : 用户：c6ef682d-da2e-4cac-a004-c244ff4c4503，注册成功，自动创建账户信息.</span><br><span class="line">2017-12-30 18:39:29.376  INFO 2781 --- [cTaskExecutor-1] c.h.rabbitmq.consumer.SendMailConsumer   : 用户：c6ef682d-da2e-4cac-a004-c244ff4c4503，注册成功，自动发送注册成功邮件.</span><br></pre></td></tr></table></figure></p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>本章主要讲解了<code>TopicExchange</code>交换类型如何消费队列消息，讲解了常用到了的特殊字符<code>#</code>、<code>*</code>如何匹配，解决了多模块下的队列配置信息无法自动创建问题。还有一点需要注意<code>TopicExchange</code>交换类型在消息消费时不存在固定的先后顺序！！！</p>
<p>本章源码已经上传到码云：<br>SpringBoot配套源码地址：<a href="https://gitee.com/hengboy/spring-boot-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-boot-chapter</a><br>SpringCloud配套源码地址：<a href="https://gitee.com/hengboy/spring-cloud-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-cloud-chapter</a><br>SpringBoot相关系列文章请访问：<a href="http://www.jianshu.com/p/9a08417e4e84" target="_blank" rel="noopener">目录：SpringBoot学习目录</a><br>QueryDSL相关系列文章请访问：<a href="http://www.jianshu.com/p/99a5ec5c3bd5" target="_blank" rel="noopener">QueryDSL通用查询框架学习目录</a><br>SpringDataJPA相关系列文章请访问：<a href="http://www.jianshu.com/p/615ed9c1fe84" target="_blank" rel="noopener">目录：SpringDataJPA学习目录</a>，感谢阅读！<br>欢迎加入QQ技术交流群，共同进步。<br><img src="http://upload-images.jianshu.io/upload_images/4461954-d80b777ca38632ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="QQ技术交流群"></p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">


    <div class="bdsharebuttonbox">
    <a href="#" class="bds_more" data-cmd="more">分享到：</a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间">QQ空间</a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博">新浪微博</a>
    <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博">腾讯微博</a>
    <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网">人人网</a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信">微信</a>
</div>
<script>
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{"bdSize":16}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<style>
    .bdshare_popup_box {
        border-radius: 4px;
        border: #e1e1e1 solid 1px;
    }
    .bdshare-button-style0-16 a,
    .bdshare-button-style0-16 .bds_more {
        padding-left: 20px;
        margin: 6px 10px 6px 0;
    }
    .bdshare_dialog_list a,
    .bdshare_popup_list a,
    .bdshare_popup_bottom a {
        font-family: 'Microsoft Yahei';
    }
    .bdshare_popup_top {
        display: none;
    }
    .bdshare_popup_bottom {
        height: auto;
        padding: 5px;
    }
</style>


</div>

            
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/spring-boot-chapter-44/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    第四十四章： 基于SpringBoot &amp; AOP完成统一资源自动查询映射
                
            </div>
        </a>
    
    
        <a href="/spring-boot-chapter-42/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">第四十二章： 基于SpringBoot &amp; RabbitMQ完成DirectExchange分布式消息多消费者消费</div>
        </a>
    
</nav>


    
</article>


    
    

</section>
            
			
				
<aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">最新文章</h3>
        <div class="widget">
            <ul id="recent-post" class="no-thumbnail">
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-52/" class="title">第五十二章：基于SpringBoot2使用Rest访问MongoDB数据</a></p>
                            <p class="item-date"><time datetime="2018-04-21T16:00:00.000Z" itemprop="datePublished">2018-04-22</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-51/" class="title">第五十一章：基于SpringBoot2 &amp; MongoDB完成自动化集成</a></p>
                            <p class="item-date"><time datetime="2018-04-15T16:00:00.000Z" itemprop="datePublished">2018-04-16</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-50/" class="title">第五十章：SpringBoot2.0新特性 - 岂止至今最简单redis缓存集成</a></p>
                            <p class="item-date"><time datetime="2018-04-14T16:00:00.000Z" itemprop="datePublished">2018-04-15</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-49/" class="title">第四十九章：SpringBoot2.0新特性 - 你get到WebMvcConfigurer两种配置方式了吗？</a></p>
                            <p class="item-date"><time datetime="2018-03-16T16:00:00.000Z" itemprop="datePublished">2018-03-17</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-48/" class="title">第四十八章：SpringBoot2.0新特性 - RabbitMQ信任package设置</a></p>
                            <p class="item-date"><time datetime="2018-03-12T16:00:00.000Z" itemprop="datePublished">2018-03-13</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">分类</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/QueryDSL-核心技术/">QueryDSL 核心技术</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a><span class="category-list-count">36</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">归档</h3>
        <div class="widget">
            <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/04/">四月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">三月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/01/">一月 2018</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/12/">十二月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/11/">十一月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/10/">十月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/09/">九月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/08/">八月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/07/">七月 2017</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/06/">六月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/05/">五月 2017</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/04/">四月 2017</a><span class="archive-list-count">5</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签</h3>
        <div class="widget">
            <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/QueryDSL/">QueryDSL</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/SpringBoot/">SpringBoot</a><span class="tag-list-count">43</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签云</h3>
        <div class="widget tagcloud">
            <a href="/tags/QueryDSL/" style="font-size: 10px;">QueryDSL</a> <a href="/tags/SpringBoot/" style="font-size: 20px;">SpringBoot</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title">链接</h3>
        <div class="widget">
            <ul>
                
                    <li>
     				<a href="http://hexo.io" target="_blank">Hexo</a>
					</li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>

				
        </div>
        <!--引入不蒜子-->
<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            <span  id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
            &copy; 2017 - 2018 恒宇少年 - 版权所有<br>
        </div>
    </div>
</footer>

        


    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>